package com.yq.controller;

import com.yq.bean.Notification;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class Server {
    public static void main(String[] args) {
        //创建套接字，指定端口
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8000);
            //监听和接收客户端的链接
            while (true) {
                System.out.println("服务端正在监听链接");
                Socket socket = serverSocket.accept();
                //创建一个线程进行处理
                new ServerThread(socket).start();
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

//服务器线程
class ServerThread extends Thread {
    boolean isRun = true;//运行状态
    Socket socket;//定义一个socket
    ObjectOutputStream oos;//先定义对象流
    ObjectInputStream ois;

    //定义构造器
    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    //服务器线程要处理操作
    @Override
    public void run() {
        try {
            //初始化对象流
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        //循环操作
        while (isRun) {
            try {
                //读数据
                Notification notification = (Notification) ois.readObject();
                String service = notification.getService();//service类名
                String action = notification.getAction();//方法名
                //获得字节码对象
                Class<?> c = Class.forName("com.yq.service." + service);
                //定义一个方法
                Method method;
                try {
                    method = c.getMethod(action, Notification.class);//获取method对象
                    //产生对象，执行方法，返回结果
                    notification = (Notification) method.invoke(c.getDeclaredConstructor().newInstance(), notification);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //写数据
                oos.writeObject(notification);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                //出现IOException，则结束线程
                isRun = false;
                System.out.println("服务器进程结束---------------------");
            }
        }

        try {
            //关闭流和socket
            ois.close();
            oos.close();
            socket.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}